const {
  sm3
} = require('sm-crypto');

var base64 = require('base-64');
var utf8 = require('utf8');

const appId = "202305220944ZY5rcED8Be6";
const appSecret = "Jjnn3c8px3Pd5B25HbpNQF7bPKmSWP6w";


function encryptReqData(paramDictionary) {
  
  var encryptDictionary = {};
  encryptDictionary["appid"] = appId;
  var data = encryptData(paramDictionary, true);
  console.log('encryptData', data);
  encryptDictionary["data"] = data;

  var currenttimemillis = (new Date().getTime() - new Date(1970, 0, 1, 0, 0, 0, 0).getTime());
  var timestamp = currenttimemillis + ""; // "1698139029626";// 

  encryptDictionary["timestamp"] = timestamp;
  var version = "1.0";
  var _sign = signNoSalt(appId, appSecret, data, timestamp, version);

  encryptDictionary["sign"] = _sign;
  encryptDictionary["version"] = version;
  return encryptDictionary;
}

function signNoSalt(appId, appSecret, data, timestamp, version) {
  const _str = `appid=${appId}&data=${data}&timestamp=${timestamp}`;
  const stringSignTemp = `${_str}&key=${appSecret}&version=${version}`;
  // log.debug("签名字符串：{}", stringSignTemp);
  const sm3 = require('sm-crypto').sm3
  return sm3(stringSignTemp);

}

function encryptData(data, sm4Encrypt) {
  console.log(data); 
  var base64Data = encode64(data);
  console.log('base64Data', base64Data);
  
    // 数据是否SM4加密
  return encryptSm4(base64Data);
  
}

function encode64(data) {
  var data_byte=utf8.encode(JSON.stringify(data));
  // var bytes = utf8.encode(data);
  return base64.encode(data_byte);
}

function decode64(data) {
  var bytes = base64.decode(data);
  return utf8.decode(bytes);
} 


function stringToHex2(s) {
  var r = "";
  var hexes = new Array("0", "1", "2", "3", "4", "5", "6", "7", "8", "9", "a", "b", "c", "d", "e", "f");
  for (var i = 0; i < s.length; i++) {
    r += hexes[s.charCodeAt(i) >> 4] + hexes[s.charCodeAt(i) & 0xf];
  }
  return r;
}

function decryptSm4(data) { 
  const sm4 = require('sm-crypto').sm4
  var hexKey = stringToHex2(appSecret.substring(0, 16));
   
  var plaintext = sm4.decrypt(data, hexKey);
  plaintext = decode64(plaintext);
  return plaintext;
}

function encryptSm4(data) {
  console.log(data);
  console.log(appSecret);
  var hexKey = stringToHex2(appSecret.substring(0, 16));
  const sm4 = require('sm-crypto').sm4
  return sm4.encrypt(data, hexKey)// 加密，默认输出 16 进制字符串，默认使用 pkcs#7 填充（传 pkcs#5 也会走 pkcs#7 填充）

}
// 导出方法
module.exports = {
  encryptReqData,
  decryptSm4
}